/*
 * @Author: Low-key 1334637865@qq.com
 * @Date: 2023-08-08 16:19:24
 * @LastEditors: Low-key 1334637865@qq.com
 * @LastEditTime: 2023-08-08 17:08:46
 * @FilePath: \crm-mobile-ui\src\axios\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from "axios";
import { Toast, Dialog } from "vant";
import { serialize } from "@/utils/index";
import router from "../router";
// import store from "@/store";
// import { getToken } from '@/utils/auth'
import qs from "qs";
// create an axios instance
const service = axios.create({
  // baseURL: "/api", // url = base url + request url
  baseURL: process.env.NODE_ENV === 'production' ? '/' : '/', 
  // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 500000 // request timeout
});

// request interceptor
service.interceptors.request.use(
  config => {
    // do something before request is sent
    config.headers["X-App-Id"] = "DATACENTER";
    config.headers["content-type"] = "application/json; charset=UTF-8";
    let token = localStorage.getItem('token');
    // console.log(token)
    if (token) {
      // let each request carry token
      // ['X-Token'] is a custom headers key
      // please modify it according to the actual situation
      // config.headers["Authorization"] = token;
      config.data.token = token;
    }
    // console.log(config);
   
    // headers中配置serialize为true开启序列化
    if (config.method === "post" && config.headers.serialize) {
      config.data = serialize(config.data);
      delete config.data.serialize;
    }
    // 处理get 请求的数组 springmvc 可以处理
    if (config.method === "get") {
      // console.log(config.paramsSerializer)
      config.paramsSerializer = function(params) {
        return qs.stringify(params, { arrayFormat: "repeat" });
      };
    }
    return config;
  },
  error => {
    // do something with request error
    return Promise.reject(error);
  }
);

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
   */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    const res = response.data;
    // if the custom code is not 20000, it is judged as an error.
    if (res.status === 1) {
      return res;
    } else {
      console.log(res.msg)
      Toast.fail(res.msg || "Error");
      if (res.status == 100 || res.status == 200) {
        localStorage.removeItem('token')
        router.push({path:'/login'})
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (res.status === 50008 || res.status === 50012 || res.status === 50014) {
        // to re-login
        Dialog.alert({
          message: "用户信息已失效，请重新登录"
        }).then(() => {
          // store.dispatch('user/resetToken').then(() => {
          //   location.reload()
          // })
        });
      }
      return Promise.reject(new Error(res.message || "Error"));
    }
  },
  error => {
    console.log(error); // for debug
    if (error.message) {
      Toast.fail(error.message || "Error");
      return Promise.reject(error);
    }
  }
);

export default service;
